﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using OA.Bll.Authority;
using OA.Model;
using OA.Utility;

namespace OA.Web.Handler
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class UserAuthorityHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            JsonReq req = JsonHelper.JsonDeserialize<JsonReq>(JsonHelper.GetPostString());
            //UserAuthority 获取用户该模块的权限  
            //Module 获取模块的权限
            string result = InitModule(req.Options["moduleTag"], req.Options["Type"]);
            context.Response.Write(result);
        }

        /// <summary>
        /// 初始化模块权限
        /// </summary>
        /// <param name="moduleTag">模块标识</param>
        public  string  InitModule(string moduleTag,string type)
        {
            StringBuilder stringBuilder = new StringBuilder();
            ModulesPresenter bll = new ModulesPresenter();
            RolesPresenter Rolebll = new RolesPresenter();
            //判断模块是否启用
            if (bll.IsModule(moduleTag))
            {
                if (SessionBox.GetUserSession().Status == 1)
                {
                    //读取模块权限
                    int id = bll.GetModuleID(moduleTag);
                    if (type == "Module")
                    {
                        List<string> mlists = new List<string>(); //模块权限
                        DataSet maLds = bll.GetAuthorityList(id);

                        for (int i = 0; i < maLds.Tables[0].Rows.Count; i++)
                        {
                            mlists.Add(maLds.Tables[0].Rows[i]["AuthorityTag"].ToString());
                        }
                        stringBuilder.Append("[");
                        foreach (string mlist in mlists)
                        {
                            stringBuilder.Append("{");
                            stringBuilder.Append(string.Format("\"AuthorityTag\": \"{0}\"", mlist));
                            stringBuilder.Append("},");
                        }
                        stringBuilder.Remove(stringBuilder.ToString().Length - 1, 1);
                        stringBuilder.Append("]");
                        return stringBuilder.ToString();
                    }
                    if (type == "UserAuthority")
                    {
                        List<string> ulists = new List<string>(); //用户的模块权限

                        #region 读取用户的所有权限

                        //读取用户角色拥有的该模块权限
                        ArrayList rid = SessionBox.GetUserSession().RoleID;
                        if (rid != null)
                        {
                            for (int ri = 0; ri < rid.Count; ri++)
                            {
                                if (!string.IsNullOrEmpty(rid[ri].ToString().Split(',')[0]))
                                {
                                    DataSet RALds =
                                        Rolebll.GetRoleAuthorityList(int.Parse(rid[ri].ToString().Split(',')[0]), id);
                                    for (int i = 0; i < RALds.Tables[0].Rows.Count; i++)
                                    {
                                        if (
                                            !UserHandle.ModuleTagExists(ulists,
                                                                        RALds.Tables[0].Rows[i]["AuthorityTag"].ToString
                                                                            ()))
                                            ulists.Add(RALds.Tables[0].Rows[i]["AuthorityTag"].ToString().ToLower());
                                    }
                                }
                            }
                        }

                        //读取用户拥有的该模块权限
                        DataSet RALUseds =
                            Rolebll.GetUserAuthorityList(Convert.ToInt32(SessionBox.GetUserSession().LoginId), id);
                        for (int i = 0; i < RALUseds.Tables[0].Rows.Count; i++)
                        {
                            if (
                                !UserHandle.ModuleTagExists(ulists,
                                                            RALUseds.Tables[0].Rows[i]["AuthorityTag"].ToString()))
                            {
                                if (RALUseds.Tables[0].Rows[i]["Flag"].ToString().ToLower() == "true")
                                {
                                    ulists.Add(RALUseds.Tables[0].Rows[i]["AuthorityTag"].ToString().ToLower());
                                }
                            }
                            else
                            {
                                if (RALUseds.Tables[0].Rows[i]["Flag"].ToString().ToLower() != "true")
                                {
                                    ulists.Remove(RALUseds.Tables[0].Rows[i]["AuthorityTag"].ToString().ToLower());
                                }
                            }
                        }

                        #endregion
                        stringBuilder.Append("[");
                        foreach (var ulist in ulists)
                        {

                            stringBuilder.Append("{");
                            stringBuilder.Append(string.Format("\"AuthorityTag\": \"{0}\"", ulist));
                            stringBuilder.Append("},");
                        }
                        stringBuilder.Remove(stringBuilder.ToString().Length - 1, 1);
                        stringBuilder.Append("]");
                        return stringBuilder.ToString();
                    }
                }
            }
            return "";
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
